package com.shuwen.gcdj.service.power;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuwen.gcdj.bean.common.response.StringStringKvItemResp;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.PowerApiAuthDept;
import com.shuwen.gcdj.mapper.mysql.PowerApiAuthDeptMapper;
import com.shuwen.gcdj.service.BaseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@AllArgsConstructor
public class PowerApiAuthDeptService extends BaseService<PowerApiAuthDeptMapper, PowerApiAuthDept> {

    private final PowerApiAuthDeptMapper powerApiAuthDeptMapper;

    /**
     * 物理删除
     *
     * @param powerApiIds List<String> t_user_power_api.id集合
     */
    public void phyDeleteByApiCode(List<String> powerApiIds) {
        if (powerApiIds == null || powerApiIds.isEmpty()) {
            return;
        }

        QueryWrapper<PowerApiAuthDept> delQuery = new QueryWrapper<>();
        delQuery.in("power_api_id", powerApiIds);
        List<PowerApiAuthDept> del = powerApiAuthDeptMapper.selectList(delQuery);
        if (del != null && !del.isEmpty()) {
            List<String> delIds = new ArrayList<>();
            for (PowerApiAuthDept p : del) {
                delIds.add(p.getId());
            }
            powerApiAuthDeptMapper.deleteBatchIds(delIds);
        }
    }

    /**
     * 绑定
     *
     * @param powerApiId  String
     * @param authDeptIds List<String>
     * @param initUserDto InitUserDto
     */
    public void bindApi(String powerApiId, List<StringStringKvItemResp> authDeptIds, InitUserDto initUserDto) {
        if (powerApiId == null || powerApiId.isEmpty()) {
            return;
        }

        if (authDeptIds == null || authDeptIds.isEmpty()) {
            return;
        }

        if (initUserDto == null) {
            initUserDto = new InitUserDto();
        }

        List<PowerApiAuthDept> ms = new ArrayList<>();
        for (StringStringKvItemResp dept : authDeptIds) {
            PowerApiAuthDept m = new PowerApiAuthDept();
            m.setPowerApiId(powerApiId);
            Optional.ofNullable(dept.getId()).ifPresent(m::setPowerApiId);
            Optional.ofNullable(initUserDto.getUserId()).ifPresent(m::setCreateId);
            Optional.ofNullable(initUserDto.getUserId()).ifPresent(m::setUpdateId);
            ms.add(m);
        }
        saveBatch(ms);
    }
}
